/*
 * @lc app=leetcode.cn id=121 lang=typescript
 *
 * [121] 买卖股票的最佳时机
 */

// @lc code=start
// 暴力法会超时
// function maxProfit(prices: number[]): number {
//     let max = 0;
//     for (let i1 = 0; i1 < prices.length; i1++) {
//         const el1 = prices[i1];
//         const el2 = Math.max(...prices.slice(i1 + 1));
//         const result = el2 - el1;
//         if (result > max) max = result;
//     }
//     return max;
// }
function maxProfit(prices: number[]): number {
    let profit = 0;
    let cost = Infinity;
    prices.forEach((price) => {
        cost = Math.min(cost, price);
        profit = Math.max(profit, price - cost);
    });
    return profit;
}
// @lc code=end
